---客户端更新api
--@functino
local DefHandle = class("CliupApi", require("framework.cls.basehandler"))

--======================================
--default params
local d = Ding
local n_req = ngx.req
local Logger = d.Logger

local resty_md5 = require("resty.md5")
local resty_upload = require("resty.upload")
local resty_str = require("resty.string")
--======================================

---构造函数
function DefHandle:ctor(svr)
	DefHandle.super.ctor(self, "cliupdate", svr)
end

--==========================================================================
--下面是用于开发调试的接口
--==========================================================================
---接收form表单文件上传
function DefHandle:post_uplaodlog()
	local function get_filename(res)
		local filename = ngx.re.match(res, '(.+)filename="(.+)"(.*)')
		if filename then
			return filename[2]
		end
	end

	local function handle_uploading()
		local dst_dir = "/data0/_back_proj"
		local chunk_size = 500 * 1024
		local form, err = resty_upload:new(chunk_size)
		if not form then
			ngx.exit(500)
		end
		local md5 = resty_md5:new()
		file_name = ""
		file = nil
		while true do
			local typ, res, err = form:read()
			if not typ then
				Logger:error("failed to read%s: ", err)
				return
			end
			if typ == "header" then
				file_name = get_filename(res[2])
				if file_name then
					file = io.open(dst_dir .. "/" .. file_name, "w+")
					if not file then
						Logger:debug("failed to open%s file ", file_name)
						return
					end
				end
			elseif typ == "body" then
				if file then
					file:write(res)
					md5:update(res)
				end
			elseif typ == "part_end" then
				if file then
					file:close()
					file = nil
				end
				local md5_sum = md5:final()
				md5:reset()
				Logger:error("md5:", resty_str.to_hex(md5_sum))
			elseif typ == "eof" then
				break
			else
				-- do nothing
			end
		end
		if file_name then
			return dst_dir .. "/" .. file_name
		else
			return "filename not get"
		end
	end
	handle_uploading()
end

return DefHandle
